﻿using System.Collections.Specialized;
using Newtonsoft.Json;

namespace CometDocs
{
    internal partial class Client
    {
        /// <summary>
        /// Authenticate to the CometDocs API: https://www.cometdocs.com/developer/apiDocumentation#method-authenticate
        /// </summary>
        /// <param name="username">The CometDocs website username (typically an email address).</param>
        /// <param name="password">The CometDocs website password.</param>
        /// <param name="key">The CometDocs API key (you can create one here: https://www.cometdocs.com/developer/myApps. </param>
        /// <param name="validity">The desired validity of the emitted token.</param>
        /// <returns>An authentication token to use with subsequent API calls.</returns>
        public AuthenticationToken Authenticate(string username, string password, string key, int? validity = null)
        {
            NameValueCollection @params = new NameValueCollection(4);
            @params.Add("username", username);
            @params.Add("password", password);
            @params.Add("clientKey", key);
            if (validity != null)
            {
                @params.Add("validity", validity.ToString());
            }

            byte[] result = webClient.UploadValues(APIRoot + "authenticate", @params);

            string json = encoding.GetString(result);

            AuthenticateResponse response = JsonConvert.DeserializeObject<AuthenticateResponse>(json);

            CheckAndThrow(response);

            return new AuthenticationToken(response.Token);
        }
    }
}
